import router from '@/router'
import { webStorage } from '@/utils/webStorage'
import { ACCESS_TOKEN, HOME_PAGE_PATH, LOGIN_PAGE_PATH } from '@/mutation-type'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
//白名单
const whiteList = [LOGIN_PAGE_PATH, HOME_PAGE_PATH, '/user/register', '/user/forget', '/news/index', '/news/detail', '/product/index', '/product/detail']
NProgress.configure({ showSpinner: false })
//路由拦截
router.beforeEach((to, from, next) => {
  updateTitle(to)
  NProgress.start()
  if (webStorage.ls.get(ACCESS_TOKEN)) {
    if (to.path === LOGIN_PAGE_PATH) {
      next({ path: HOME_PAGE_PATH })
    } else {
      next()
    }
    NProgress.done()
  } else {
    if (whiteList.find((item) => item == to.path)) {
      //白名单不校验token，放行
      next()
    } else {
      next({ path: LOGIN_PAGE_PATH, query: { redirect: to.fullPath } })
    }
    NProgress.done()
  }
})
router.afterEach(() => {
  NProgress.done() // finish progress bar
})

/**
 * 更新浏览器标题
 * @param route
 */
function updateTitle(route) {
  let names = []
  if (route && route.meta && route.meta.title) {
    names.push(route.meta.title)
  }
  document.title = names.join(' - ')
}
